/**
 * Created by Administrator on 2018/6/22.
 */

function formatDataSankey(data){
    var nodes = {}, links = {}, index = 0, root = "班子成员", sp = "_link_", cacheNode = [];
    nodes[root + sp + 0] = index;
    cacheNode.push([root + sp + 0, index++]);
    ////// 节点索引 //////
    data.forEach(function(line){
        line.forEach(function(d, i){
            if(i<1)return;                     ////// 过滤第一列 //////
            var n = d + sp + i;
            if(!(n in nodes)){
                cacheNode.push([n, index]);     ////// 用于排序 //////
                nodes[n] = index++;             ////// 用于查询 //////
            }
        });
    });
    ////// 生成边 //////
    data.forEach(function(item){
        var line = item.map(function(d, i){ return i===0 ? root : d; });          ////// 替换第一列 //////
        line.forEach(function(e, i){
            if(i<1)return;
            var lk = line[i - 1] + sp + line[i];
            if(!(lk in links))links[lk] = {"value": 0, "src":[i-1, i] };
            links[lk].value++;
        })
    });

    ////// 数据输出 //////
    var dts = {"nodes" : [], "links" : []}, rowCount = data.length;
    dts.nodes = cacheNode.sort(function(a, b){ return a[1] - b[1]; })
        .map(function(d){
            //cout(d[0]);
            var tp = d[0].split(sp);
            //cout(tp[0] + "_" + d[1]);

            return {"name":d[0].split(sp)[0], "id":tp[1] + "_" + tp[0]};
            return {"name":d[0].split(sp)[0], "id":d[0]};
        });

    for(var lk in links){
        var tps = links[lk].src, parts = lk.split(sp);
        var s = parts[0] + sp + tps[0], t = parts[1] + sp + tps[1];
        dts.links.push({"source":nodes[s], "target":nodes[t], "value":links[lk].value / rowCount});
    }

    //cout(dts);
    //cout(JSON.stringify(dts));

    return dts;
}


function drawSanKey(id, data){
    $("#"+id).html("");
    data = data || [
        ["id", "男", "青", "共产党", "经济学","5年以下",  "县　长", "刘　超"],
        ["id", "男", "青", "共产党", "经济学","5-10年", "副县长", "颜　超"],
        ["id", "男", "青", "共产党", "管理学","5-10年", "副县长", "杨学宁"],
        ["id", "男", "青", "共产党", "管理学","5-10年", "副县长", "王明华"],
        ["id", "男", "青", "共产党", "法学",  "5-10年", "副县长", "经大忠"],
        ["id", "男", "青", "民进党", "法学", "10-15年", "副县长", "孙福全"],
        ["id", "男", "中", "共产党", "法学", "10-15年", "副县长", "韩圣健"],
        ["id", "女", "中", "共产党", "工学", "10-15年", "副县长", "蒋丽英"],
        ["id", "男", "中", "共产党", "工学", "10-15年", "副县长", "罗宗志"],
        ["id", "男", "中", "共产党", "理学", "15-20年", "副县长", "赵迎春"],
        ["id", "男", "老", "共产党", "历史学", "15-20年", "副县长", "罗　蒙"],
        ["id", "男", "老", "共产党", "农学", "25年以上", "副县长", "谭 岗"],
        ["id", "男", "中", "共产党", "历史学", "20-25年", "县长助理", "张胜"],
        ["id", "男", "老", "农工党", "农学", "20-25年", "县长助理", "文剑"]
    ];

    var colors = {
        '0': '#edbd00',
        '1': '#367d85',
        '2': '#97ba4c',
        '3': '#f5662b',
        '4': '#97ba4c',
        '5': '#367d85',
        '6': '#edbd00',
        '7': '#367d85',
        '8': '#0f2fa3'
    };
    //d3.json("product.json", function(error, json) {
    var json = formatDataSankey(data);
    var chart = d3.select("#" + id).append("svg").chart("Sankey.Path");
    chart.setDataCache(data);
    chart
        .name(label)
        .colorNodes(function(name, node) {
            return color(node, 1) || colors.fallback;
        })
        .colorLinks(function(link) {
            return color(link.source, 4) || color(link.target, 1) || colors.fallback;
        })
        .nodeWidth(15)
        .nodePadding(10)
        .spread(true)
        .iterations(0)
        .draw(json);
    function label(node) {
        return node.name.replace(/\s*\(.*?\)$/, '');
    }
    function color(node, depth) {
        var id = node.id.replace(/(_score)?(_\d+)?$/, '');
        id = id.split("_")[0];
        if (colors[id]) {
            return colors[id];
        } else if (depth > 0 && node.targetLinks && node.targetLinks.length == 1) {
            return color(node.targetLinks[0].source, depth-1);
        } else {
            return null;
        }
    }
    //});


}

function drawItem(id, data, info, title){
    var spirit = "image://";
    data = data.sort(function(a, b){ return a.value - b.value; });
    var names = data.map(function(d){ return d.name; });
    var values = data.map(function(d){ return d.value; });
    var maxData = values.reduce(function(a, b){ return a + b; }, 0);
    cout(maxData);
    var option = {
        "title": {
            //"text": "象形柱图",
            "left": "center",
            "y": "10",
            "textStyle": {
                "color": "#fff"
            }
        },
        //"backgroundColor": "#F8F8FF",//"#101a3c",
        "grid": {
            "left": "15%",
            "top": "5%",
            "right": 10,
            "bottom": 10
        },
        "tooltip": {
            "trigger": "item",
            "textStyle": {
                "fontSize": 12
            },
            "formatter": "{b0}:{c0}"
        },
        "xAxis": {
            "max": 10,
            "splitLine": {
                "show": false
            },
            "axisLine": {
                "show": false
            },
            "axisLabel": {
                "show": false
            },
            "axisTick": {
                "show": false
            }
        },
        "yAxis": [
            {
                "type": "category",
                "inverse": false,
                "data": names,
                "axisLine": {
                    "show": false
                },
                "axisTick": {
                    "show": false
                },
                "axisLabel": {
                    "margin": -4,
                    "textStyle": {
                        "color": "#00f",
                        "fontSize": 16.25
                    }
                }
            },

        ],
        "series": [
            {
                "type": "pictorialBar",
                "symbol": spirit,
                "symbolRepeat": "fixed",
                "symbolMargin": "28%",
                "symbolClip": true,
                "symbolSize": 22.5,
                "symbolPosition": "start",
                "symbolOffset": [20, 0],
                "symbolBoundingData": 100,
                "data": values,
                "z": 10
            },
            {
                "type": "pictorialBar",
                "itemStyle": {
                    "normal": { "opacity": 0.2 }
                },
                "label": {
                    "normal": { "show": false }
                },
                "animationDuration": 0,
                "symbolRepeat": "fixed",
                "symbolMargin": "28%",
                "symbol": spirit,
                "symbolSize": 22.5,
                "symbolBoundingData": 100,
                "symbolPosition": "start",
                "symbolOffset": [ 20, 0],
                "data": values,
                "z": 5
            }
        ]
    };

    Init3(option ,id);

    function random() {
        return +(Math.random() * (maxData - 10)).toFixed(1);
    }

}


function getGraphData(dts){
    var data = {
        "categories": [
            {
                "name": "上游",
                "text": "",
            }],
        "nodes": [
            {
                "name": "公司名称A",
                "value": 1,
                "category": 4
            }],
        "links": [
            {
                "source": 0,
                "target": 1,
                "relation": 0
            }]
        };
    var index = 0, cacheC = dts.reduce(function(a, b){ if(!(b[6] in a))index++; a[b[6]] = index - 1; return a; }, {});
    data.categories = Object.keys( cacheC).map(function(d){ return { "name":d }; });
    var rels = ['同事', '校友', '亲属', '老乡'];
    data.categories = rels.map(function(d){ return { "name":d }; });

    data.nodes = dts.map(function(d){
        return { "name": d[7] + " " + d[1],
            "value": parseInt(Math.random() * 4),
            "category": cacheC[d[6]]
        };
    });
    data.links = [];
    var r = function(){ return parseInt(Math.random() * dts.length); };
    for(var i=0; i<Math.random() * 10 + 2; i++){
        var s = r(), t = r(), rel = ['同事', '校友', '亲属', '老乡'][parseInt(Math.random() * 4)];
        if(s==t) continue;
        data.links.push({
            "source": s,
            "target": t,
            "relation": rel
        });
    }
    cout(cacheC);
    return data;
}


function drawGraph(id, data){
    var graph = data;
    var categories = graph.categories;//.map(function(d){ return {name:d.name}; });

    graph.nodes.forEach(function (node) {
        node.itemStyle = null;
        node.symbolSize = node.value * 2 + 9;
        node.label = {
            normal: {
                show: node.symbolSize > 1
            }
        };
    });
    var option = {
        title: {
            text: '班子成员关系网络',
            subtext: '任职回避',
            top: 'top',
            left: 'left'
        },
        legend: [{
            orient:'vertical', right:80, top:20,
            data: categories.map(function (a) {
                return a.name;
            })
        }],
        animationDuration: 3000,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            type: 'graph',
            layout: 'force',
            force: {
                repulsion: 300
            },
            data: graph.nodes,
            links: graph.links,
            categories: categories,
            focusNodeAdjacency: true,
            roam: true,
            label: {
                normal: {
                    show: true,
                    position: 'top',
                }
            },
            lineStyle: {
                normal: {
                    color: 'source',
                    curveness: 0,
                    type: "solid"
                }
            }
        }]
    };

    Init3(option, id);
}


function setTable(graph){
    function f(d){ return d.substr(0, d.length - 2); }
    var body = graph.links.filter(function(d){
        return true;
    }).map(function(d){
        var styleS = ' style = "color:' + (d.source==0 ? 'red' : '#000') + '"';
        var styleT = ' style = "color:' + (d.target==0 ? 'red' : '#000') + '"';
        return "<tr>" +
            "<td"+ styleS + ">" + f(graph.nodes[d.source].name) + "</td>" +
            "<td"+ styleT + ">" + f(graph.nodes[d.target].name) + "</td>" +
            "<td>"+ d.relation + "</td>" +
            "<td>"+ "时间" + "</td>" +
            // "<td>"+ (2002 + parseInt(Math.random() * 15) ) + "</td>" +
            + "</tr>"; }).join("");
    $("#tbody1").html(body);
}


function drawGraphC(id, data){
    var graph = data;
    var categories = graph.categories;//.map(function(d){ return {name:d.name}; });
    setTable(graph);

    graph.nodes.forEach(function (node) {
        node.itemStyle = null;
        node.symbolSize = node.value * 2 + 9;
        node.label = {
            normal: {
                show: node.symbolSize > 1
            }
        };
    });
    var option = {
        title: {
            text: '班子成员关系网络',
            subtext: '任职回避',
            top: 'top',
            left: 'left'
        },
        tooltip: {},
        legend: [{
            orient:'vertical', right:80, top:20,
            data: categories.map(function (a) {
                return a.name;
            })
        }],
        animationDurationUpdate: 1500,
        animationEasingUpdate: 'quinticInOut',
        series : [
            {
                name: '班子成员',
                type: 'graph',
                layout: 'circular',
                circular: {
                    rotateLabel: false
                },
                data: graph.nodes,
                links: graph.links,
                categories: categories,
                roam: true,
                label: {
                    normal: {
                        position: 'right',
                        formatter: '{b}'
                    }
                },
                lineStyle: {
                    normal: {
                        color: 'source',
                        curveness: 0.3
                    }
                },
                edgeLabel: {
                    normal: {
                        show: true,
                        textStyle: {
                            fontSize: 11, color:'red'
                        },
                        formatter: function(p){
                            return p.data.relation;
                        }
                    }
                }
            }
        ]
    };

    Init3(option, id);


}




function drawBar(id, data){
    var Color = ['#3b7186', '#2e8d94', '#637b69', '#789b6f',
        '#3b64a6', '#2672cc', '#503e8d', '#5d3ec5',
        '#874f5f', '#b6575c', '#623363', '#962e66'
    ];
    data = data.sort(function(a, b){ return a.value - b.value; });
    var xs = data.map(function(d){ return d.name; });
    var values = data.map(function(d){ return d.value; });

    var option = {
        //backgroundColor: '#131e54',
        grid: {
            left: '3%',
            right: '4%',
            bottom: '10%',
            containLabel: true
        },

        tooltip: {
            show: "true",
            trigger: 'item',
            formatter: '{b}<br />{a0}: {c0}',
            backgroundColor: 'rgba(0,0,0,0.7)', // 背景
            padding: [8, 10], //内边距
            extraCssText: 'box-shadow: 0 0 3px rgba(255, 255, 255, 0.4);', //添加阴影
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        xAxis: {
            type: 'value',
            position: 'top',
            axisTick: {
                show: false
            },
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#32346c',
                }
            },
            splitLine: {
                show: false,
                lineStyle: {
                    color: '#32346c ',
                }
            },
            axisLabel: {
                textStyle: {
                    color: '#bac0c0',
                    fontWeight: 'normal',
                    fontSize: '12',
                },
                formatter: '{value}',
            },
        },
        yAxis: {
            type: 'category',
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#eeeeee'
                }
            },
            splitLine: {
                show: false
            },
            axisTick: {
                show: false
            },
            splitArea: {
                show: false
            },
            axisLabel: {
                inside: false,
                textStyle: {
                    color: '#000',
                    fontWeight: 800,
                    fontSize: '14',
                },
            },
            data:xs
        },
        series: [{
            name: '综合评价',
            type: 'bar',
            itemStyle: {
                normal: {
                    show: true,
                    color: function(params) {
                        var colorList = [];
                        for (var i = 6; i > 0; i--) {
                            colorList.push({
                                type: 'bar',
                                colorStops: [{
                                    offset: 0,
                                    color: Color[i*2 - 2] // 0% 处的颜色
                                }, {
                                    offset: 1,
                                    color: Color[i*2 - 1] // 100% 处的颜色
                                }],
                                globalCoord: false, // 缺省为 false

                            });
                        }

                        return colorList[params.dataIndex]
                    },
                    barBorderRadius: 50,
                    borderWidth: 0,
                    borderColor: '#333',
                }
            },
            label:{ show:true, position:'insideRight' },
            barGap: '0%',
            barCategoryGap: '50%',
            data: values
        }

        ]
    };

    Init3(option, id);
}